package com.guigu.xm.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
@Primary
@Aspect
public class MyAdivce {
     /*     @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  @Pointcut(" execution(* com.guigu.xm.lq.controller.*.*(..))")
  @Pointcut("@annotation(com.guigu.xm.advice.Interceptor)")
    @Pointcut("execution(* com.guigu.xm.lq.service.impl.*Impl.*(..))")更加灵活*/

    @Pointcut("@annotation(com.guigu.xm.advice.Interceptor)")
    public void pointcut(){ }

    @After("MyAdivce.pointcut()")
    public void after(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String login_id = (String)request.getSession().getAttribute("login_id");
        Signature signature = joinPoint.getSignature();
        MethodSignature msg=(MethodSignature) signature;
        Object target = joinPoint.getTarget();
        //获取注解标注的方法
        Method method = null;
        try {
            method = target.getClass().getMethod(msg.getName(), msg.getParameterTypes());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        //通过方法获取到自定义的注解
        Interceptor annotation = method.getAnnotation(Interceptor.class);
        if(annotation!=null) {
            //记录日志 看实际情况，日志存表入库
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(annotation.methodName());
        }
    }
}
